package cz.apnetis.fitweb.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

import cz.apnetis.fitweb.shared.Calorie;
import cz.apnetis.fitweb.shared.dto.CalorieEntity;

public class CalorieEditWidget extends Composite {

  private static CalorieEditWidgetUiBinder uiBinder = GWT
      .create(CalorieEditWidgetUiBinder.class);

  private final CalorieServiceAsync calorieService = GWT.create(CalorieService.class);

  interface CalorieEditWidgetUiBinder extends
      UiBinder<Widget, CalorieEditWidget> {
  }

  @UiField
  Button button;
  @UiField
  Hidden key;
  @UiField
  TextBox name;
  @UiField
  TextBox cal;
  @UiField
  TextBox joule;

  public CalorieEditWidget() {
    initWidget(uiBinder.createAndBindUi(this));
  }

  @UiHandler("button")
  void onClick(ClickEvent e) {

    Calorie calorie = new CalorieEntity();
    calorie.setKey(key.getValue());
    calorie.setName(name.getText());
    calorie.setCal(Integer.valueOf(cal.getText()));
    calorie.setJoule(Integer.valueOf(joule.getText()));

    calorieService.saveCalorie(calorie, new AsyncCallback<Calorie>() {

      @Override
      public void onFailure(Throwable caught) {
        
      }

      @Override
      public void onSuccess(Calorie result) {
        key.setValue(result.getKey());
        name.setText(result.getName());
        cal.setText(result.getCal().toString());
        joule.setText(result.getJoule().toString());
      }
    });
  }
}
